package com.hoperay.util;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.UnicodeProperties;
import com.liferay.portlet.expando.DuplicateTableNameException;
import com.liferay.portlet.expando.model.ExpandoColumn;
import com.liferay.portlet.expando.model.ExpandoTable;
import com.liferay.portlet.expando.model.ExpandoTableConstants;
import com.liferay.portlet.expando.service.ExpandoColumnLocalServiceUtil;
import com.liferay.portlet.expando.service.ExpandoTableLocalServiceUtil;

public class CustomFieldUtil {
	public static ExpandoColumn createField(String fieldName, int fieldType, String className, boolean hidden, long companyId) {
		
		ExpandoTable table = getTable(companyId, className);
		
		ExpandoColumn column = null;
		try {
			column = ExpandoColumnLocalServiceUtil.addColumn(
					table.getTableId(), fieldName, fieldType);
		} catch (PortalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// setting this as a hidden column
		UnicodeProperties props = column.getTypeSettingsProperties();
		if (hidden) {
			props.setProperty("hidden", "1");
		}
		column.setTypeSettingsProperties(props);
		try {
			ExpandoColumnLocalServiceUtil.updateExpandoColumn(column);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return column;
	}
	
	private static ExpandoTable getTable(long companyId, String className) {
		
		ExpandoTable table = null;
		try {
			table = ExpandoTableLocalServiceUtil.addTable(companyId, className, ExpandoTableConstants.DEFAULT_TABLE_NAME);
		} catch (PortalException e) {
			// TODO Auto-generated catch block
			
			if (e instanceof DuplicateTableNameException) {
				try {
					table = ExpandoTableLocalServiceUtil.getTable(companyId,
							className, ExpandoTableConstants.DEFAULT_TABLE_NAME);
				} catch (PortalException e1) {
					// TODO Auto-generated catch block
				} catch (SystemException e1) {
					// TODO Auto-generated catch block
				}
			}
		} catch (SystemException e) {
			// TODO Auto-generated catch block
		}
		return table;
	}
}
